<template>
  <a-layout style="">
    <!-- 内容 -->
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
    >
      <div class="tableEdit">
        <a-input-search
          v-model:value="value"
          placeholder="input search text"
          enter-button
          @search="onSearch"
          size="large"
          class="custom-search-input"
        />
        <a-button type="primary" @click="add()" size="large"> 新增 </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="ebooks"
        :pagination="pagination"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <!-- 分类 -->
          <template v-if="column.key === 'name'">
            <a>
              {{ record.name }}
            </a>
          </template>
          <!-- 编辑 -->
          <template v-else-if="column.key === 'action'">
            <span>
              <router-link :to="'/admin/doc?ebookId=' + record.id">
                <a-button type="primary"> 文档树 </a-button>
              </router-link>

              <a-button type="primary" @click="edit(record)"> 编辑 </a-button>
              <a-divider type="vertical" />

              <a-popconfirm
                title="Are you sure delete this task?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="primary" danger> 删除 </a-button>
              </a-popconfirm>
            </span>
          </template>

          <template v-else-if="column.key === 'category'">
            <span
              >{{ getCategoryName(record.category1Id) }} /
              {{ getCategoryName(record.category2Id) }}</span
            >

            <!-- <span>{{ record.category1Id }} / {{ record.category2Id }}</span> -->
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
    title="电子书表单"
    v-model:open="modalVisible"
    :confirm-loading="modalLoading"
    @ok="handleModalOk"
    ok-text="确认"
    cancel-text="取消"
  >
    <a-form :model="ebook" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover" />
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
          v-model:value="categoryIds"
          :field-names="{ label: 'name', value: 'id', children: 'children' }"
          :options="CategoryTree"
        ></a-cascader>
      </a-form-item>

      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" type="textarea" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, Ref } from "vue";
import { useApi } from "@/api";
import { message } from "ant-design-vue";
import { Tool } from "@/utils/tool";
import {  EBook, Pagination } from "@/views/type";

const api = useApi();
const loading = ref(false);

import useEbooks from "@/store/bookstore";
import useCategory from "@/store/categorystore";

const ebookStore = useEbooks();
const ecategoryStore = useCategory();

//表格的列
const columns = [
  {
    title: "封面",
    dataIndex: "cover",
    key: "cover",
  },
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "分类",
    dataIndex: "category",
    key: "category",
  },
  {
    title: "文档数",
    dataIndex: "docCount",
    key: "docCount",
  },
  {
    title: "阅读数",
    dataIndex: "viewCount",
    key: "viewCount",
  },
  {
    title: "点赞数",
    dataIndex: "voteCount",
    key: "voteCount",
  },
  {
    title: "Action",
    key: "action",
  },
];

//分页初始化
const pagination: Ref<Pagination> = ref({
  current: 1,
  pageSize: 100,
  total: 0,
});

console.log("000000")
onMounted(async () => {
  await ecategoryStore.getECategory(); // 获取分类
  await ebookStore.getEbooks({
    page: pagination.value.current,
    size: pagination.value.pageSize,
  }); // 更新电子书数据
});






// ----------------- 请求数据 先获取分类数据 在获取电子书数据 -----------------

//树形分类
const CategoryTree =  computed(()=> ecategoryStore.categoryTree )
const ebooks = computed(() => { return ebookStore.ebooks; })
ebookStore.getEbooks({
  page: pagination.value.current,
  size: pagination.value.pageSize,
});

//store  获取电子书  book电子书数据查询

// 从 store 中映射电子书数据，确保响应式

console.log("ebooks", ebooks)

  //重置分页按钮
  pagination.value = {
    ...pagination.value,
  current: pagination.value.current,
  total: ebookStore.total,
};

// --------------页面加载完成-----------------
const value = ref<string>("");

// //二.表格方法

// -----------book新增电子书表单 Model对话框--------------
// 先编辑再对话框,

const modalVisible = ref(false);
const modalLoading = ref(false);

//分类数据合并对象
let categoryIds = ref<number[]>([1]);

const ebook = ref<EBook>({
  name: "",
  category1Id: 0,
  category2Id: 0,
  description: "",
  docCount: 0,
  viewCount: 0,
  voteCount: 0,
});
/**
 * 1.编辑分类
 */
const edit = (record: EBook) => {
  modalVisible.value = true;
  ebook.value = Tool.copy(record);
  categoryIds.value[0] = ebook.value.category1Id!;
  categoryIds.value[1] = ebook.value.category2Id!;
};

/**
 * 1-1.对话框新增电子书表单
 */
const handleModalOk = async () => {
  ebook.value.category1Id = categoryIds.value[0];
  ebook.value.category2Id = categoryIds.value[1];

  await api.saveBook(ebook.value);

  message.success("书本保存成功");

  // 重新加载列表
  ebookStore.getEbooks({
    page: pagination.value.current,
    size: pagination.value.pageSize,
  });
};

/**
 *
 * 2. 删除
 */
const handleDelete = async (id: number) => {
  await api.deleteBook(id);
  ebookStore.getEbooks({
    page: pagination.value.current,
    size: pagination.value.pageSize,
  });
};

//一.头部方法

/**
 *  1.新增
 */
const add = () => {
  modalVisible.value = true;
  ebook.value = {
    name: "",
    description: "",
    cover: "",
    docCount: 0,
    viewCount: 0,
    voteCount: 0,
  };
};
// 2.搜索
const onSearch = async (searchValue: string) => {
 
  ebookStore.getEbooks({name: searchValue});
};

/**
 * 获取id对应的中文分类
 **/
const getCategoryName = (cid: number): string => {
  return ecategoryStore.categoryMap.get(cid)!;
};
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
.tableEdit {
  display: flex;
  flex-direction: row;
  justify-content: start;
}
.custom-search-input {
  width: 30%;
}
</style>
